<template>
  <div v-title data-title="主页面">
    <!--container是大容器-->
    <el-container style="height: 100vh; border: 1px solid #eee">
      <!--aside是左侧导航栏-->
      <el-aside width="145px" style="background-color: rgb(238, 241, 246)">
        <!--:default-active=""-->
        <el-menu :default-openeds="['2', '3']" router>
          <span :key="index" v-for="(item, index) in $router.options.routes">
            <el-submenu
              @click.native="changeMenuCatalog(index)"
              :index="index + ''"
              v-if="index > 1"
            >
              <template slot="title"
                ><i class="el-icon-setting"></i>
                {{ item.name }}
              </template>

              <span :key="index" v-for="(subitem, index) in item.children">
                <el-menu-item
                  style="text-align: left"
                  :class="$route.path == subitem.path ? 'is-active' : ''"
                  :index="subitem.path"
                >
                  {{ subitem.name }}
                </el-menu-item>
              </span>
            </el-submenu>
          </span>
        </el-menu>
      </el-aside>

      <el-container>
        <!--头部信息-->
        <el-header
          style="border: 1px solid #eee; text-align: right; font-size: 12px"
        >
          <div>
            <el-breadcrumb style="margin-top: 20px" separator="/">
              <el-breadcrumb-item
                @click.native="showFirstPageContent"
                :to="{ path: '/home' }"
              >
                {{
                  $router.options.routes[this.$store.getters.getMenuCatalog]
                    .name
                }}
              </el-breadcrumb-item>

              <span
                :key="index"
                v-for="(item, index) in $router.options.routes[
                  this.$store.getters.getMenuCatalog
                ].children"
              >
                <el-breadcrumb-item v-if="$route.path == item.path"
                  ><a href="#">{{ item.name }}</a>
                </el-breadcrumb-item>
              </span>
            </el-breadcrumb>

            <span class="welcome">欢迎您 {{ infoForm.username }}</span>

            <el-dropdown :style="cursorStyle">
              <el-avatar id="profile" :src="circleUrl"></el-avatar>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="logout">注销</el-dropdown-item>
                <el-dropdown-item @click.native="completeInfo"
                  >完善个人信息</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-header>

        <el-main>
          <!--这里是显示path对应页面的template内容 比如pageOne就是找pageOne对应的template内容-->
          <router-view></router-view>

          <!--个人信息对话框-->
          <el-dialog
            title="个人信息完善"
            :visible.sync="dialogVisible"
            width="60%"
          >
            <el-form
              :rules="infoFormRules"
              ref="infoForm"
              :model="infoForm"
              label-width="80px"
            >
              <el-form-item prop="username" label="用户名">
                <el-input
                  :readonly="'readonly'"
                  type="text"
                  v-model="infoForm.username"
                  autocomplete="off"
                >
                </el-input>
              </el-form-item>

              <el-form-item prop="name" label="姓名">
                <el-input
                  type="text"
                  v-model="infoForm.name"
                  autocomplete="off"
                >
                </el-input>
              </el-form-item>

              <el-form-item prop="email" label="邮箱">
                <el-input
                  :readonly="'readonly'"
                  type="text"
                  v-model="infoForm.email"
                  autocomplete="off"
                >
                </el-input>
              </el-form-item>

              <el-form-item prop="time" label="出生日期">
                <el-date-picker
                  v-model="infoForm.birth"
                  type="date"
                  placeholder="选择日期时间"
                >
                </el-date-picker>
              </el-form-item>

              <el-form-item prop="phonenum" label="电话号码">
                <el-input
                  type="text"
                  v-model="infoForm.phonenum"
                  autocomplete="off"
                >
                </el-input>
              </el-form-item>

              <span>专业信息：</span>
              <el-cascader
                v-model="value"
                :options="options"
                :props="{ expandTrigger: 'hover' }"
              >
              </el-cascader>
            </el-form>

            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="uploadInfo('infoForm')"
                >确 定</el-button
              >
            </span>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
// 使用刚指定的配置项和数据显示图表。
import Home from "../components/Home";
import main from "/src/main.js";
import store from "/src/store/index.js";

export default {
  name: "Index",
  data() {
    let _this = this;
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号码!"));
      } else {
        if (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(value)) {
          callback(new Error("手机号码有误，请重新填写!"));
        } else {
          let _data = this.$data;
          //查一下数据库 有没有已经存在了
          axios
            .get(main.requestAddress + "/user/isExistsPhone/" + value, {
              params: { username: _this.infoForm.username },
            })
            .then(function (response) {
              //从后端返回给前端的内容(code、message、data...等等)
              let flag = response.data.data;
              if (flag == true) {
                _this.$message.error("该手机号已被绑定！");
              }
            })
            .catch(function (error) {
              alert(error);
            });
        }
        callback();
      }
    };
    return {
      index: 2,
      value: [],
      options: [],
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      user: [],
      infoFormRules: {
        username: [
          {
            required: true,
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱不可为空",
            trigger: "blur",
          },
        ],
        phonenum: [
          {
            validator: validatePhone,
            trigger: "blur",
          },
        ],
      },
      dateForm: {
        time: "",
      },
      infoForm: {
        username: "",
        name: "",
        email: "",
        phonenum: "",
        birth: "",
        department: "",
        major: "",
      },
      dialogVisible: false,
      index: "",
      cursorStyle: "cursor:pointer;",
    };
  },
  mounted() {},
  methods: {
    changeMenuCatalog(index) {
      //改变页面导航信息
      this.$store.commit("setMenuCatalog", index);
    },
    uploadInfo(formName) {
      const _this = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (_this.value.length === 0) {
            _this.$message.error("请您选择学院信息！");
            return;
          }

          //上传用户的学院及专业
          let department = this.value[0];
          let major = this.value[1];

          //赋给infoForm表单 后台接受User对象
          this.infoForm.department = department;
          this.infoForm.major = major;

          //POST方法 上传用户个人信息
          this.$axios
            .post(main.requestAddress + `/user/uploadInfo`, _this.infoForm)
            .then((res) => {
              let updateNum = res.data.data;
              if (updateNum == 1) {
                //如果上传信息成功
                _this.$message.success("信息上传成功！");
                this.dialogVisible = false;
              }
            })
            .catch((Error) => {
              console.log(Error);
            });
        } else {
          return false;
        }
      });
    },
    showFirstPageContent() {
      this.$data.firstPageContentShow = true;
    },
    logout() {
      sessionStorage.setItem("token", false);
      this.$message({
        showClose: true,
        message: "注销成功",
        type: "success",
      });
      setTimeout(location.reload(), 3000); //2秒后再执行
    },
    changeToLandscape() {
      this.$notify({
        title: "警告",
        message: "您好，为避免显示错误，请您将手机切换成横屏显示！",
        type: "warning",
        position: "bottom-right",
      });
    },
    notifyMoveToDown() {
      this.$notify({
        title: "温馨提示",
        message: "滑动左侧导航栏灰色区域向下查看",
        type: "info",
        position: "bottom-left",
      });
    },
    completeInfo() {
      this.dialogVisible = true;
    },
  },
  created() {
    //初始化学院&专业 JSON数据

    let _this = this;
    axios
      .get(main.requestAddress + "/user/getJson", {
        params: { jsonName: "Department.json" },
      })
      .then(function (response) {
        //从后端返回给前端的内容(code、message、data...等等)
        let departments = response.data.data.Departments;
        for (let i = 0; i < departments.length; i++) {
          _this.options.push(departments[i]);
        }
      })
      .catch(function (error) {
        alert(error);
      });

    //避免重复跳转 如果当前路由就是 /home 就不跳转
    if (this.$route.path !== "/home") {
      this.$router.push({ path: "/home" });
    }

    //在整个生命周期 该函数只会被进入一次！
    //初始用户的信息 而不是每点一次完善个人信息 就查询一遍
    let username = sessionStorage.getItem("username");
    axios
      .get(main.requestAddress + "/user/getUserInfoByUsername", {
        params: { info_username: username },
      })
      .then(function (response) {
        let datalist = response.data.data;
        //依次绑定至前端

        if (username === "visitor") {
          _this.infoForm.username = "游客";
        } else {
          _this.infoForm.username = datalist.username;
        }

        _this.infoForm.email = datalist.email;
        _this.infoForm.phonenum = datalist.phonenum;
        _this.infoForm.name = datalist.name;
        _this.infoForm.birth = datalist.birth;
        _this.value[0] = datalist.department;
        _this.value[1] = datalist.major;
        _this.$message.info(response.data.message);
      })
      .catch(function (error) {
        alert(error);
      });

    // 竖屏时才提醒用户
    if (window.orientation == 180 || window.orientation == 0) {
      //js判断当前移动设备平台
      let isIOS = false;
      let isAndroid = false;
      let isWindowsPhone = false;
      if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
        isIOS = true;
      } else if (/(Android)/i.test(navigator.userAgent)) {
        isAndroid = true;
      } else if (/(Windows Phone)/i.test(navigator.userAgent)) {
        isWindowsPhone = true;
      }
      if (isIOS | isAndroid | isWindowsPhone) {
        this.$message.success("检测您当前为移动设备登录");
        this.changeToLandscape();
      }
    }
    //横屏提醒
    if (window.orientation == 90 || window.orientation == -90) {
      this.notifyMoveToDown();
    }
  },
  //挂载组件
  components: {
    "my-component-home": Home,
    "my-component-history": History,
  },
};
</script>

<style >
.el-submenu .el-menu-item {
  min-width: 0px;
}
#profile {
  margin-top: -20px;
}
</style>